const state = {

	// 购物车的数组，用来存储购物车中每个商品的信息对象
	// { goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state }
	cart: JSON.parse(uni.getStorageSync('cart') || '[]')

}

const mutations = {
	// 添加到购物车
	ADDTOCART(state, goods) {
		const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
		if (!findResult) {
			state.cart.push(goods)
		} else {
			findResult.goods_count++
		}
		this.commit('m_cart/saveToStorage')
	},

	// 将购物车的数据持久化到本地
	saveToStorage(state) {
		uni.setStorageSync('cart', JSON.stringify(state.cart))
	},

	// 更新购物车中商品的勾选状态
	UPDATEGOODSSTATE(state, goods) {
		const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
		if (findResult) {
			findResult.goods_state = goods.goods_state
			this.commit('m_cart/saveToStorage')
		}
	},

	// 更新购物车的商品数量
	UPDATEGOODSCOUNT(state, goods) {
		const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
		if (findResult) {
			findResult.goods_count = goods.goods_count
			this.commit('m_cart/saveToStorage')
		}
	},

	// 根据商品的id删除购物车
	REMOVEGOODSBYID(state, goods_id) {
		state.cart = state.cart.filter(x => x.goods_id !== goods_id)
		this.commit('m_cart/saveToStorage')
	},

	// 更新购物车中的商品选中状态
	UPDATEALLGOODSSTATE(state, newState) {
		state.cart.forEach(x => x.goods_state = newState)
		this.commit('m_cart/saveToStorage')
	}
}

const actions = {
	// 添加到购物车
	addToCart({
		commit
	}, goods) {
		commit('ADDTOCART', goods)
	},

	// 修改购物车的选中状态
	updateGoodsState({
		commit
	}, goods) {
		commit('UPDATEGOODSSTATE', goods)
	},

	// 更新购物车的商品数量
	updateGoodsCount({
		commit
	}, goods) {
		commit('UPDATEGOODSCOUNT', goods)
	},

	// 根据商品的id删除购物车
	removeGoodsById({
		commit
	}, goods_id) {
		commit('REMOVEGOODSBYID', goods_id)
	},

	// 更新购物车中的商品选中状态
	updateAllGoodsState({
		commit
	}, newState) {
		commit('UPDATEALLGOODSSTATE', newState)
	}
}

const getters = {
	// 获取购物车商品总数量
	total(state) {
		return state.cart.reduce((total, item) => total += item.goods_count, 0)
	},

	// 已勾选的商品总数量
	checkedCount(state) {
		return state.cart.filter(x => x.goods_state).reduce((total, item) => total += item.goods_count, 0)
	},

	// 已勾选的商品的总价
	checkedGoodsAmount(state) {
		return state.cart.filter(x => x.goods_state).reduce((total, item) => total += item.goods_count * item
			.goods_price, 0).toFixed(2)
	}
}


export default {
	// 为当前模块开启命名空间
	namespaced: true,
	state,
	mutations,
	actions,
	getters
}
